package JUC.CountDownLatch和cyclicBarrier和Semaphore的使用;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;

/**
 * @author CKC
 * @DateTime 2021/3/31 19:49
 * <p>
 * 使用场景：
 * CyclicBarrier初始化时规定一个数目，然后计算调用了CyclicBarrier.await()进入等待的线程数。
 * 当线程数达到了这个数目时，所有进入等待状态的线程被唤醒并继续。
 */
//@SuppressWarnings("all")
public class CyclicBarrierDemo {

    public static void main(String[] args) throws InterruptedException {
        //public CyclicBarrier(int parties, Runnable barrierAction)
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println(Thread.currentThread().getName() + "\t 召唤神龙");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            final int tem = i;
            Thread thread = new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t 收集到第：" + tem + "龙珠");
                try {
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i));
            list.add(thread);
            thread.start();
        }
        Thread.sleep(500);
        list.forEach(thread -> {
            System.out.println(thread.getName() + ":   " + thread.getState());
        });

        //for (int i = 0; i < 7; i++) {
        //    final int tem = i;
        //    new Thread(() -> {
        //        System.out.println(Thread.currentThread().getName() + "\t 收集到第：" + tem + "龙珠");
        //        try {
        //            cyclicBarrier.await();
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //        }
        //    }, String.valueOf(i)).start();
        //}

    }
}
